local returnDown = hs.eventtap.event.newKeyEvent({}, "return", true)
local returnUp = hs.eventtap.event.newKeyEvent({}, "return", false)

local function sendEnter()
	returnDown:post()
	returnUp:post()
end

hs.hotkey.bind({ "ctrl" }, "m", sendEnter)

-- =============================================
-- Ctrl+H 连续删除优化方案
-- 版本 1.2 - 支持长按连续删除
-- =============================================

-- 终端应用列表 (可扩展)
local terminalApps = {
	"com.apple.Terminal",
	"com.googlecode.iterm2",
	"co.zeit.hyper",
	"net.kovidgoyal.kitty",
}

-- 预创建事件对象 (性能优化)
local backspaceDown = hs.eventtap.event.newKeyEvent({}, "delete", true)
local backspaceUp = hs.eventtap.event.newKeyEvent({}, "delete", false)
local ctrlHDown = hs.eventtap.event.newKeyEvent({ "ctrl" }, "h", true)
local ctrlHUp = hs.eventtap.event.newKeyEvent({ "ctrl" }, "h", false)

-- 状态跟踪变量
local isCtrlHPressed = false
local isBackspacing = false
local backspaceTimer = nil
local backspaceRepeatRate = 0.05 -- 50ms (20次/秒)
local initialDelay = 0.3 -- 300ms 初始延迟

-- 智能终端检测函数
local function isTerminalApp()
	local app = hs.application.frontmostApplication()
	local bundleID = app and app:bundleID() or ""

	for _, termID in ipairs(terminalApps) do
		if bundleID == termID then
			return true
		end
	end

	return false
end

-- 开始连续删除
local function startContinuousBackspace()
	if isBackspacing then
		return
	end
	isBackspacing = true

	-- 初始删除
	backspaceDown:post()
	backspaceUp:post()

	-- 设置重复定时器
	backspaceTimer = hs.timer.doWhile(function()
		return isCtrlHPressed
	end, function()
		backspaceDown:post()
		backspaceUp:post()
	end, backspaceRepeatRate)
end

-- 停止连续删除
local function stopContinuousBackspace()
	if backspaceTimer then
		backspaceTimer:stop()
		backspaceTimer = nil
	end
	isBackspacing = false
end

-- Ctrl+H 按下处理
local function onCtrlHDown()
	if isTerminalApp() then
		-- 在终端中发送 Ctrl+H
		ctrlHDown:post()
		ctrlHUp:post()
		return
	end

	isCtrlHPressed = true

	-- 设置初始延迟定时器
	hs.timer.doAfter(initialDelay, function()
		if isCtrlHPressed then
			startContinuousBackspace()
		end
	end)
end

-- Ctrl+H 释放处理
local function onCtrlHUp()
	isCtrlHPressed = false
	stopContinuousBackspace()
end

-- 创建热键绑定
hs.hotkey.new({ "ctrl" }, "h", onCtrlHDown, nil, onCtrlHUp)
